# -*- coding: utf-8 -*-
# frontend/utils/ui_helpers.py
"""
UI辅助函数
"""

import streamlit as st
from typing import Dict, Any, List
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import pandas as pd

def display_model_badge(model_name: str) -> str:
    """显示模型徽章"""
    model_info = {
        "gpt-4": {"name": "GPT-4", "color": "#10a37f", "icon": "🧠"},
        "gpt-3.5-turbo": {"name": "GPT-3.5", "color": "#10a37f", "icon": "⚡"},
        "claude-3": {"name": "Claude-3", "color": "#d97706", "icon": "🤖"},
        "gemini-pro": {"name": "Gemini", "color": "#4285f4", "icon": "💎"}
    }
    
    info = model_info.get(model_name, {"name": model_name, "color": "#666", "icon": "🤖"})
    
    return f"""
    <span class="model-badge" style="background-color: {info['color']}; color: white;">
        {info['icon']} {info['name']}
    </span>
    """

def format_timestamp(timestamp: str) -> str:
    """格式化时间戳"""
    try:
        dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
        now = datetime.now()
        
        if dt.date() == now.date():
            return f"今天 {dt.strftime('%H:%M')}"
        elif dt.date() == (now - timedelta(days=1)).date():
            return f"昨天 {dt.strftime('%H:%M')}"
        else:
            return dt.strftime('%m-%d %H:%M')
    except:
        return timestamp

def create_usage_chart(usage_data: Dict[str, int]) -> go.Figure:
    """创建使用统计图表"""
    fig = px.pie(
        values=list(usage_data.values()),
        names=list(usage_data.keys()),
        title="AI模型使用分布",
        color_discrete_map={
            "gpt-4": "#10a37f",
            "claude-3": "#d97706", 
            "gemini-pro": "#4285f4"
        }
    )
    
    fig.update_traces(textposition='inside', textinfo='percent+label')
    fig.update_layout(height=400)
    
    return fig

def create_conversation_timeline(conversations: List[Dict]) -> go.Figure:
    """创建对话时间线图表"""
    if not conversations:
        return go.Figure()
    
    df = pd.DataFrame(conversations)
    df['date'] = pd.to_datetime(df['created_at']).dt.date
    daily_counts = df.groupby('date').size().reset_index(name='count')
    
    fig = px.line(
        daily_counts, 
        x='date', 
        y='count',
        title="每日对话数量趋势",
        markers=True
    )
    
    fig.update_layout(
        xaxis_title="日期",
        yaxis_title="对话数量",
        height=400
    )
    
    return fig

def show_loading_animation(text: str = "处理中..."):
    """显示加载动画"""
    return st.empty().markdown(f"""
    <div style="text-align: center; padding: 2rem;">
        <div style="display: inline-block; width: 40px; height: 40px; border: 4px solid #f3f3f3; border-top: 4px solid #667eea; border-radius: 50%; animation: spin 1s linear infinite;"></div>
        <p style="margin-top: 1rem; color: #666;">{text}</p>
    </div>
    <style>
        @keyframes spin {
            '0% {{ transform: rotate(0deg); }}'
            '100% {{ transform: rotate(360deg); }}'
        }
    </style>
    """, unsafe_allow_html=True)
